package com.book.manager.service;

import cn.hutool.core.bean.BeanUtil;
import com.book.manager.dao.MsgMapper;
import com.book.manager.entity.Users;
import com.book.manager.entity.msg;
import com.book.manager.repos.MsgRepository;
import com.book.manager.util.ro.PageIn;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class MsgService  {

    @Autowired
    MsgMapper msgMapper;
    @Autowired
    MsgRepository msgRepository;

    public msg addMsg(msg msg) {
        //向用戶發送郵件

        return msgRepository.saveAndFlush(msg);
    }

    /**
     * 用户搜索查询(mybatis 分页)
     * @param pageIn
     * @return
     */
    public PageInfo<msg> getMsgList(PageIn pageIn) {

        PageHelper.startPage(pageIn.getCurrPage(),pageIn.getPageSize());
        List<msg> listByLike = msgMapper.findMsgListByLike(pageIn.getKeyword());
        return new PageInfo<>(listByLike);
    }

    /**
     * 编辑消息
     * @param msg 消息对象
     * @return true or false
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean updateMsg(msg msg) {
        return msgMapper.updateMsg(BeanUtil.beanToMap(msg))>0;
    }

    /**
     * 删除消息
     * @param msgid 主键
     * @return true or false
     */
    public String deleteMsg(Integer msgid) {

        try {
            msgRepository.deleteById(msgid);
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
        return "";
    }

    /**
     * 消息详情
     * @param id 主键
     * @return 消息详情
     */
    public msg findMsgById(Integer id) {
        Optional<msg> optional = msgRepository.findById(id);
        if (optional.isPresent()) {
            return optional.get();
        }
        return null;
    }

}
